using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using star_questionnair.Models;
using star_questionnair.Models.Enum;

namespace star_questionnair.Services.impl;

public class LevelQuestionAnalysisService : ILevelQuestionAnalysisService
{
    private readonly IQuestionService _questionService;
        private readonly IHistoryService _historyService;

        public LevelQuestionAnalysisService(IQuestionService questionService, IHistoryService historyService)
        {
            _questionService = questionService;
            _historyService = historyService;
        }

        public async Task<double?> GetAverageScoreAsync(int questionId)
        {
            var question = await _questionService.GetQuestionByIdAsync(questionId);

            // 判断是否为等级题类型
            if (!QuestionEnumExtensions.IsLevelType(question.Type))
            {
                return null;
            }

            // 获取该问题的所有答案
            var answers =  _historyService.GetAnswersByQuestionId(questionId);

            int countAnswer = answers.Count;
            int totalScore = 0;

            // 计算总分
            foreach (var answer in answers)
            {
                totalScore += answer.Level;
            }

            if (countAnswer == 0)
            {
                return 0.0;
            }

            return (double)totalScore / countAnswer;
        }

        public async Task<Dictionary<int, double>> GetLevelRankingProportionsAsync(int questionId)
        {
            var question = await _questionService.GetQuestionByIdAsync(questionId);

            // 判断是否为等级题类型
            if (!QuestionEnumExtensions.IsLevelType(question.Type))
            {
                return null;
            }

            // 获取该问题的所有答案
            var answers =  _historyService.GetAnswersByQuestionId(questionId);

            // 初始化每个level的计数器
            var levelCounts = new Dictionary<int, int>();
            for (int i = 1; i <= 5; i++)
            {
                levelCounts[i] = 0;
            }

            // 统计每个level的出现次数
            foreach (var answer in answers)
            {
                int level = answer.Level;
                levelCounts[level]++;
            }

            // 计算每个level的比例
            var levelProportions = new Dictionary<int, double>();
            int totalAnswers = answers.Count;
            for (int i = 1; i <= 5; i++)
            {
                int count = levelCounts[i];
                double proportion = totalAnswers == 0 ? 0.0 : (double)count / totalAnswers;
                levelProportions[i] = proportion*100 ;
            }

            return levelProportions;
        }
}